#include "types.h"
#include "stat.h"
#include "fcntl.h"
#include "user.h"
#include "fs.h"

/* coppied from ls.c */

char*
fmtname(char *path)
{
	static char buf[DIRSIZ+1];
	char *p;

	// Find first character after last slash.
	for(p=path+strlen(path); p >= path && *p != '/'; p--)
		;
	p++;

	// Return blank-padded name.
	if(strlen(p) >= DIRSIZ)
		return p;
	memmove(buf, p, strlen(p));
	memset(buf+strlen(p), ' ', DIRSIZ-strlen(p));
	return buf;
}

void
ls(char *path)
{
	char buf[512], *p;
	int fd;
	struct dirent de;
	struct stat st;

	if((fd = open(path, 0)) < 0){
		printf(2, "ls: cannot open %s\n", path);
		return;
	}

	if(fstat(fd, &st) < 0){
		printf(2, "ls: cannot stat %s\n", path);
		close(fd);
		return;
	}

	switch(st.type){
	case T_FILE:
		printf(1, "%s %d %d %d\n", fmtname(path), st.type, st.ino, st.size);
		break;

	case T_DIR:
		if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
			printf(1, "ls: path too long\n");
			break;
		}
		strcpy(buf, path);
		p = buf+strlen(buf);
		*p++ = '/';
		while(read(fd, &de, sizeof(de)) == sizeof(de)){
			if(de.inum == 0)
				continue;
			memmove(p, de.name, DIRSIZ);
			p[DIRSIZ] = 0;
			if(stat(buf, &st) < 0){
				printf(1, "ls: cannot stat %s\n", buf);
				continue;
			}
			printf(1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size);
		}
		break;
	}
	close(fd);
}

void childRun(char* buf) {
	int  i;
	int fd = open("4.swap", 0);
	read(fd, buf, 10);
	printf(1, "10 first bytes from father's swap file:\n");
	for (i = 1; i <= 10; i++, buf++)
		printf(1, "%x ", (unsigned char) (*buf));
	printf(1, "\n");
	close(fd);
	ls(".");
	exit();
}

void fatherRun(char* buf) {
	int  i;
	sleep(1000);
	buf = (char*) 0;
	printf(1, "10 first bytes from father's memory:\n");
	for (i = 0; i < 10; i++, buf++)
		printf(1, "%x ", (unsigned char) (*buf));
	printf(1, "\n");
	wait();
}

int main(void)
{
	unsigned long int uint0 = (uint) 10 * sizeof(char);
	printf(1,"\n\n-------------- Start Swaptest ---------------\n\n");
	char *buf = malloc(uint0);
	printf(1,"First ls, should not include any swap files (Swapping disabled)\n");
	sleep(500);
	ls(".");
	printf(1,"Now enabling swapping. Next ls should include 4.swap (father's sleeping)\n");
	sleep(500);
	enableSwapping();
	int fid = fork();
	if (fid == 0){
		childRun(buf);
	}
	else
	{
		fatherRun(buf);
	}

	printf(1,"Now disabling swapping and sleeping. on the next ls, no swap files should appear\n");
	disableSwapping();
	sleep(200);
	ls(".");
	printf(1,"\n\n-------------- End Swaptest ---------------\n\n");
	exit();
	return 0;
}
